<?php

namespace app\admin\controller;

use app\common\controller\Backend;

class TextBooks extends Backend

{
    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\admin\model\TextBooks();
        $this->catalogues = new \app\admin\model\textbooks\Catalogues;
        $this->resources = new \app\admin\model\textbooks\Resources;
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);

    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['versionId'=>$ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 单元
     */
    public function unit()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $ids = input('ids/d');
            $tarr = [];
            if ($ids) {
                $tarr['unitid'] = $ids;
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->catalogues
                ->where($tarr)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 单元单词列表
     *
     */
    public function wordlist($ids)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $ids = input('ids/d');
            $tarr = [];
            if ($ids) {
                $tarr['unitid'] = $ids;
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->resources
                ->where($tarr)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 单词详情
     */
    public function questions($ids)
    {
        $hsr = $this->resources->where('versionId',$ids)->find();
        if (!$hsr) {
            $this->error(__('No Results were found'));
        }
        $hsr['resourceUrl_full'] = fileurl($hsr['resourceUrl'],true);

        $resource = json_decode(file_get_contents($hsr['resourceUrl_full'].'/resource/resource.json'),true);
        // halt($resource);
        // $resource_h5 = json_decode(file_get_contents($hsr['resourceUrl_full'].'/resource/resource_h5.json'),true);
        $this->view->assign("resourceName", $hsr['resourceName']);
        $this->view->assign("resmain", fileurl('/file/textbook_synchronization/res/',true));
        $this->view->assign("resource", $resource);
        // $this->view->assign("resource_h5", $resource_h5);
        return $this->view->fetch();
    }

}